package com.jianganming.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NioClient {
    public static void main(String[] args)throws Exception {
        Selector selector=Selector.open();
        SocketChannel socketChannel=SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("localhost",9999));
        socketChannel.register(selector, SelectionKey.OP_CONNECT); //连接事件

        while (true){
            if(selector.select(1000)==0){
                //System.out.println("服务器等待了1秒，无连接");
                continue;
            }
            //获取选择器的key
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

            while (iterator.hasNext()){

                SelectionKey key = iterator.next();
                //如果获得连接
                if(key.isConnectable()){
                    //注册
                    handleConnect(socketChannel,selector);
                }
                //如果是可读状态
                if(key.isReadable()){
                    //读取数据
                    readData(key);
                }

                iterator.remove();
            }
        }
    }

    private static void handleConnect(SocketChannel socketChannel, Selector selector)throws Exception {
        if(socketChannel.isConnectionPending()){
            //
            socketChannel.finishConnect();
        }
        String string = "你好，我是客户端";
        ByteBuffer byteBuffer = ByteBuffer.wrap(string.getBytes());

        socketChannel.write(byteBuffer);

        //注册为可读的通道
        socketChannel.register(selector,SelectionKey.OP_READ);
    }

    private static void readData(SelectionKey key)throws Exception {
        SocketChannel channel = (SocketChannel)key.channel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        int count = channel.read(byteBuffer);
        if(count !=-1){
            System.out.println(new String(byteBuffer.array(),0,count));
        }
        //将缓冲区的数组指向0位置
        byteBuffer.flip();
        //清除缓冲区的数据
        byteBuffer.clear();
    }


}
